package chu.dejian.db;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import chu.dejian.conf.BLEPreference;
import chu.dejian.entity.MeasureMessageEntity;

public class DBHelper extends SQLiteOpenHelper {
	private static DBHelper instance;
	public static synchronized boolean init(Context context){
		instance = new DBHelper(context);
		return instance == null ? false : true;
	}


	public static synchronized DBHelper getInstance(){
		if(instance == null) throw new NullPointerException("必须先调用DBHelper.init(context)进行初始化，才能通过getInstance获取到实例");
		return instance;
	}

	private static final String DATABASE_NAME = "bp_";
	private static final int DATABASE_VERSION = 5;

	public DBHelper(Context context) {
		super(context, DATABASE_NAME+ BLEPreference.getInstance().getAccount("default"), null,DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase database) {
		database.execSQL(RecordDao.RECORD_TABLE_CREATE);
		database.execSQL(MeasureMessageDao.MESSAGE_TABLE_CREATE);
		database.execSQL(AttendeesDao.ATTENDEE_TABLE_CREATE);
		database.execSQL(ReceivedRequestDao.RECEIVED_REQUEST_TABLE_CREATE);
		database.execSQL(SendedRequestDao.SENDED_REQUEST_TABLE_CREATE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase database, int arg1, int arg2) {
		database.execSQL("DROP TABLE IF EXISTS " + RecordDao.RECORD_TABLE);
		database.execSQL("DROP TABLE IF EXISTS " + MeasureMessageDao.MESSAGE_TABLE);
		database.execSQL("DROP TABLE IF EXISTS " + AttendeesDao.ATTENDEE_TABLE);
		database.execSQL("DROP TABLE IF EXISTS " + ReceivedRequestDao.RECEIVED_REQUEST_TABLE);
		database.execSQL("DROP TABLE IF EXISTS " + SendedRequestDao.SENDED_REQUEST_TABLE);
		onCreate(database);

	}

	public SQLiteDatabase getDatabase() throws SQLException {
		try {
			return getWritableDatabase();
		} catch(Exception e) {
			Log.e("SamLog",e.getMessage());
		}
		return null;
	}

	private static RecordDao recordDao;
	public RecordDao getRecordDao(){
		if(recordDao == null){
			recordDao = new RecordDao();
		}
		return recordDao;
	}

	private static MeasureMessageDao messageDao;
	public MeasureMessageDao getMessageDao(){
		if(messageDao == null) messageDao = new MeasureMessageDao();
		return messageDao;
	}
	private static AttendeesDao attendeesDao;
	public AttendeesDao getAttendeesDao(){
		if(attendeesDao == null) attendeesDao = new AttendeesDao();
		return attendeesDao;
	}
	private static ReceivedRequestDao receivedRequestDao;
	public ReceivedRequestDao getReceivedRequestDao(){
		if(receivedRequestDao == null) receivedRequestDao = new ReceivedRequestDao();
		return receivedRequestDao;
	}
	private static SendedRequestDao sendedRequestDao;
	public SendedRequestDao getSendedRequestDao(){
		if(sendedRequestDao == null) sendedRequestDao = new SendedRequestDao();
		return sendedRequestDao;
	}
}
